<?php
session_start();

$install_file = 'config/installed.txt';
if (!file_exists($install_file)) {
    header('Location: install.php');
    exit;
}

require_once 'config/config.php';
require_once 'api_handler.php';

$lang = $_GET['lang'] ?? $_SESSION['lang'] ?? 'en';
$_SESSION['lang'] = $lang;

// Get selected model from session or use default from config
$selected_model = $_SESSION['selected_model'] ?? $default_model ?? 'gpt-3.5-turbo';

$api_handler = new APIHandler($api_base_url, $api_key, $pdo, $lang, $selected_model);

$message = '';
$ai_response = '';
$user_input = '';
$chat_history = [];
$prompts = [];

if ($_POST) {
    if (isset($_POST['send_message'])) {
        $user_input = trim($_POST['user_input'] ?? '');
        
        if (!empty($user_input)) {
            try {
                $ai_response = $api_handler->sendRequest($user_input);
            } catch (Exception $e) {
                $message = $api_handler->getText('error') . ': ' . $e->getMessage();
            }
        } else {
            $message = $api_handler->getText('please_enter_message');
        }
    } elseif (isset($_POST['update_prompt'])) {
        $new_prompt = trim($_POST['new_prompt'] ?? '');
        
        if (!empty($new_prompt)) {
            if ($api_handler->updatePrompt($new_prompt)) {
                $message = $api_handler->getText('prompt_updated_successfully');
            } else {
                $message = $api_handler->getText('error_updating_prompt');
            }
        } else {
            $message = $api_handler->getText('please_enter_new_prompt');
        }
    } elseif (isset($_POST['update_chat'])) {
        $timestamp = $_POST['chat_timestamp'] ?? '';
        $new_content = $_POST['chat_content'] ?? '';
        $content_type = $_POST['content_type'] ?? 'user_input';
        
        if ($api_handler->updateChatMessage($timestamp, $new_content, $content_type)) {
            $message = $api_handler->getText('prompt_updated_successfully');
        } else {
            $message = $api_handler->getText('error_updating_prompt');
        }
    }
}

$chat_history = $api_handler->getChatHistory(10);
$user_chat_history = $api_handler->getUserChatHistory();
$current_prompt = $api_handler->getCurrentPrompt();
?>

<!DOCTYPE html>
<html lang="<?php echo $lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>lanxAI - 首个览星自研AI</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1, h2 {
            color: #333;
        }
        .chat-container {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 20px;
            max-height: 400px;
            overflow-y: auto;
            background-color: #fafafa;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 4px;
        }
        .user-message {
            background-color: #e3f2fd;
            text-align: right;
        }
        .ai-message {
            background-color: #f1f8e9;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        textarea, input[type="text"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        textarea {
            height: 80px;
        }
        button {
            background-color: #007cba;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #005a87;
        }
        .message-box {
            color: green;
            margin-bottom: 15px;
        }
        .error-box {
            color: red;
            margin-bottom: 15px;
        }
        .prompt-section {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }
        .chat-history-section {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }
        .language-switcher {
            float: right;
            margin-bottom: 20px;
        }
        .edit-form {
            display: none;
            margin-top: 10px;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 4px;
        }
        .edit-btn {
            background-color: #ffc107;
            color: black;
            padding: 5px 10px;
            margin-left: 5px;
        }
        .edit-btn:hover {
            background-color: #e0a800;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="language-switcher">
            <a href="?lang=en">English</a> | <a href="?lang=zh">中文</a>
        </div>
        
        <h1>lanxAI - 首个览星自研AI</h1>
        <p><?php echo $api_handler->getText('ai_assistant_ready'); ?></p>
        
        <?php if ($message): ?>
            <div class="<?php echo strpos($message, $api_handler->getText('error')) !== false ? 'error-box' : 'message-box'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <div class="chat-container">
            <?php if (!empty($user_chat_history)): ?>
                <?php foreach (array_reverse($user_chat_history) as $chat): ?>
                    <div class="message user-message">
                        <strong><?php echo $api_handler->getText('user'); ?>:</strong> <?php echo htmlspecialchars($chat['user_input']); ?>
                        <small style="display: block; color: #666;"><?php echo date('M j, Y g:i A', strtotime($chat['timestamp'])); ?></small>
                    </div>
                    <div class="message ai-message">
                        <strong><?php echo $api_handler->getText('ai'); ?>:</strong> <?php echo htmlspecialchars($chat['ai_response']); ?>
                        <small style="display: block; color: #666;"><?php echo date('M j, Y g:i A', strtotime($chat['timestamp'])); ?></small>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
            
            <?php if ($ai_response): ?>
                <div class="message user-message">
                    <strong><?php echo $api_handler->getText('user'); ?>:</strong> <?php echo htmlspecialchars($user_input); ?>
                </div>
                <div class="message ai-message">
                    <strong><?php echo $api_handler->getText('ai'); ?>:</strong> <?php echo htmlspecialchars($ai_response); ?>
                </div>
            <?php endif; ?>
        </div>
        
        <form method="POST" action="">
            <div class="form-group">
                <label for="user_input"><?php echo $api_handler->getText('your_message'); ?>:</label>
                <textarea id="user_input" name="user_input" placeholder="<?php echo $api_handler->getText('your_message'); ?>..."><?php echo htmlspecialchars($user_input); ?></textarea>
            </div>
            <button type="submit" name="send_message"><?php echo $api_handler->getText('send_message'); ?></button>
        </form>
        
        <div class="prompt-section">
            <h2><?php echo $api_handler->getText('manage_ai_prompt'); ?></h2>
            <p><strong><?php echo $api_handler->getText('current_prompt'); ?>:</strong> <?php echo htmlspecialchars($current_prompt); ?></p>
            
            <form method="POST" action="" style="margin-top: 15px;">
                <div class="form-group">
                    <label for="new_prompt"><?php echo $api_handler->getText('update_prompt'); ?>:</label>
                    <textarea id="new_prompt" name="new_prompt" placeholder="<?php echo $api_handler->getText('update_prompt'); ?>..."></textarea>
                </div>
                <button type="submit" name="update_prompt"><?php echo $api_handler->getText('update_prompt'); ?></button>
            </form>
        </div>
        
        <div class="chat-history-section">
            <h2><?php echo $api_handler->getText('chat_history'); ?></h2>
            <?php if (!empty($user_chat_history)): ?>
                <?php foreach ($user_chat_history as $index => $chat): ?>
                    <div class="message user-message">
                        <strong><?php echo $api_handler->getText('user'); ?>:</strong> 
                        <span id="user-content-<?php echo $index; ?>"><?php echo htmlspecialchars($chat['user_input']); ?></span>
                        <button class="edit-btn" onclick="toggleEditForm(<?php echo $index; ?>, '<?php echo $chat['timestamp']; ?>', 'user_input', <?php echo $lang === 'zh' ? 'true' : 'false'; ?>)"><?php echo $api_handler->getText('edit'); ?></button>
                        <small style="display: block; color: #666;"><?php echo $api_handler->getText('timestamp'); ?>: <?php echo htmlspecialchars($chat['timestamp']); ?></small>
                    </div>
                    <div class="message ai-message">
                        <strong><?php echo $api_handler->getText('ai'); ?>:</strong> 
                        <span id="ai-content-<?php echo $index; ?>"><?php echo htmlspecialchars($chat['ai_response']); ?></span>
                        <button class="edit-btn" onclick="toggleEditForm(<?php echo $index; ?>, '<?php echo $chat['timestamp']; ?>', 'ai_response', <?php echo $lang === 'zh' ? 'true' : 'false'; ?>)"><?php echo $api_handler->getText('edit'); ?></button>
                        <small style="display: block; color: #666;"><?php echo $api_handler->getText('timestamp'); ?>: <?php echo htmlspecialchars($chat['timestamp']); ?></small>
                    </div>
                    
                    <div id="edit-form-<?php echo $index; ?>" class="edit-form">
                        <form method="POST" action="">
                            <input type="hidden" name="chat_timestamp" value="<?php echo htmlspecialchars($chat['timestamp']); ?>">
                            <input type="hidden" name="content_type" value="user_input">
                            <textarea name="chat_content"><?php echo htmlspecialchars($chat['user_input']); ?></textarea>
                            <button type="submit" name="update_chat"><?php echo $api_handler->getText('save'); ?></button>
                            <button type="button" onclick="toggleEditForm(<?php echo $index; ?>, '<?php echo $chat['timestamp']; ?>', 'user_input', <?php echo $lang === 'zh' ? 'true' : 'false'; ?>)"><?php echo $api_handler->getText('cancel'); ?></button>
                        </form>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p><?php echo $api_handler->getText('no_chat_history'); ?></p>
            <?php endif; ?>
        </div>
    </div>
    
    <script>
        function toggleEditForm(index, timestamp, type, isChinese) {
            const form = document.getElementById('edit-form-' + index);
            const userContent = document.getElementById('user-content-' + index);
            const aiContent = document.getElementById('ai-content-' + index);
            const formElement = form.querySelector('form');
            
            if (form.style.display === 'block') {
                form.style.display = 'none';
                if (type === 'user_input') {
                    userContent.style.display = 'inline';
                } else {
                    aiContent.style.display = 'inline';
                }
            } else {
                // Hide all other edit forms
                const allForms = document.querySelectorAll('.edit-form');
                allForms.forEach(f => f.style.display = 'none');
                
                // Hide all content spans
                const allUserContents = document.querySelectorAll('[id^="user-content-"]');
                const allAiContents = document.querySelectorAll('[id^="ai-content-"]');
                allUserContents.forEach(c => c.style.display = 'none');
                allAiContents.forEach(c => c.style.display = 'none');
                
                // Show current edit form
                form.style.display = 'block';
                formElement.querySelector('input[name="content_type"]').value = type;
                
                // Set the form's textarea value to the current content
                if (type === 'user_input') {
                    formElement.querySelector('textarea[name="chat_content"]').value = userContent.textContent;
                } else {
                    formElement.querySelector('textarea[name="chat_content"]').value = aiContent.textContent;
                }
            }
        }
    </script>
</body>
</html>
